package com.whz.governance.redislimiter.tool;

import com.whz.governance.redislimiter.command.AtomicCounterCommand;
import com.whz.governance.redislimiter.command.AtomicCounterResult;
import com.whz.governance.redislimiter.command.ScriptParams;
import lombok.experimental.UtilityClass;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author whz
 */
@UtilityClass
public class AtomicCounterUtils {
    private static final AtomicCounterCommand COMMAND = new AtomicCounterCommand();

    /**
     * 指定时长内原子计数,达到最大技术阈值返回false
     *
     * @param key      指定的key
     * @param seconds  指定时长(秒数)
     * @param capacity 最大技术阈值
     * @return 返回是否达到阈值和剩余次数
     */
    public AtomicCounterResult execute(String key, int seconds, int capacity) {
        Assert.hasText(key, "key not null");
        Assert.isTrue(seconds > 0, "seconds > 0");
        Assert.isTrue(capacity > 0, "capacity > 0");
        ScriptParams params = ScriptParams.create()
                                          .addKey(key)
                                          .addArg(capacity + "")
                                          .addArg(seconds + "");
        List<Long> execute = COMMAND.execute(params);
        AtomicCounterResult result = new AtomicCounterResult();
        result.setPermit(execute.get(0) == 1);
        result.setLeftTimes(execute.get(1));
        return result;
    }
}